Vue Js Displays the current position of the
mouse on the screen : To display the mouse/cursor position on the screen using Vue JS, you can use Vue’s built-in event handling and data binding capabilities. First, create a div element that will hold the cursor position information. Then, add a mousemove event listener to the parent element of the div using Vue’s @mousemove directive. In the event handler function, update the div’s text content with the current mouse position using Vue’s data binding syntax {{}}. Finally, use CSS to style the div and position it on the
screen. This will continuously update the cursor position as the user moves their mouse over the parent element. In this tutorial we will learn how to display current position of Mouse in Vue Js using native javascript method
How can you display the mouse/cursor position on the screen using Vue JS?
To display the mouse/cursor position on the screen using Vue JS, you can follow these steps.
HTML:
<p>Mouse position: {{ mouseX }}, {{ mouseY }}</p>:
creates a paragraph element that displays the x and y coordinates of the mouse
JavaScript:
data() { ... }
: defines the data for the Vue application, which in this case is an object containingmouseX
andmouseY
properties with initial values of 0mounted() { ... }
: adds an event listener to the document for the “mousemove” event, which updates themouseX
andmouseY
data properties of the Vue application when the mouse is moved
Vue Js Display Mouse Position on Screen Example
<div id="app">
<p>Mouse position: {{ mouseX }}, {{ mouseY }}</p>
</div>
<script type="module">
const app = Vue.createApp({
data() {
return {
mouseX: 0,
mouseY: 0
}
},
mounted() {
document.addEventListener("mousemove", (event) => {
this.mouseX = event.clientX;
this.mouseY = event.clientY;
});
},
});
app.mount('#app');
</script>